# coding=utf-8

import requests
import json
import time
import hmac
import hashlib
import base64
import urllib.parse


def _get_timestamp_and_sign(secret):
    """获取时间戳和密钥 https://ding-doc.dingtalk.com/document#/org-dev-guide/custom-robot"""
    timestamp = str(round(time.time() * 1000))
    secret_enc = secret.encode('utf-8')
    string_to_sign = '{}\n{}'.format(timestamp, secret)
    string_to_sign_enc = string_to_sign.encode('utf-8')
    hmac_code = hmac.new(secret_enc, string_to_sign_enc, digestmod=hashlib.sha256).digest()
    sign = urllib.parse.quote_plus(base64.b64encode(hmac_code))
    return timestamp, sign


def send_message(data, access_token, secret, at_all=False, at_mobiles=''):
    # 请求参数 可以写入配置文件中
    timestamp, sign = _get_timestamp_and_sign(secret=secret)
    data['at'] = {
        'atMobiles': at_mobiles.split(','),
        "isAtAll": at_all,
    }
    # 机器人的webhooK 获取地址参考：https://open-doc.dingtalk.com/microapp/serverapi2/qf2nxq
    webhook = "https://oapi.dingtalk.com/robot/send?access_token=" + access_token
    webhook += "&timestamp=" + timestamp
    webhook += "&sign=" + sign
    headers = {'content-type': 'application/json'}  # 请求头
    r = requests.post(url=webhook, headers=headers, data=json.dumps(data))
    r.encoding = 'utf-8'
    return r.content
